package com.guangfeng.yql.redis.util;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class RedisCacheUtil {
    private static RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate",RedisTemplate.class);

    public static <T, V> void setCacheObject(T key, V value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public static <T, V> V getCacheObject(T key) {
        return (V) redisTemplate.opsForValue().get(key);
    }

    public static <T, V> void setCacheList(T key, List<V> value) {
        delete(key);
        redisTemplate.boundListOps(key).rightPushAll(value);
    }

    public static <T, V> void appendCacheList(T key, V... value) {
        redisTemplate.opsForList().rightPushAll(key, value);
    }

    public static <T, V> List<V> getCacheList(T key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }


    public static <T, V> Set<V> getCacheSet(T key) {
        return redisTemplate.opsForSet().members(key);
    }

    public static <T, V> void setCacheSet(T key, Set<V> value) {
        delete(key);
        redisTemplate.boundSetOps(key).intersect(value);
    }

    public static <T, V> boolean setExist(T key, V value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    public static <T, V> void appendCacheSet(T key, V... value) {
        redisTemplate.opsForSet().add(key, value);
    }

    public static <T, K, V> void appendCacheMap(T key, K hkey, V value) {
        redisTemplate.boundHashOps(key).put(hkey, value);
    }

    public static <T, K, V> void setCacheMap(T key, Map<K, V> map) {
        redisTemplate.boundHashOps(key).putAll(map);
    }

    public static <T, K> Set<K> getCacheMap(T key) {
        return redisTemplate.opsForHash().keys(key);
    }

    public static <T, K, V> V getCacheMap(T key, K hkey) {
        return (V) redisTemplate.opsForHash().get(key, hkey);
    }

    public static <T> void delete(T key) {
        redisTemplate.delete(key);
    }

    public static <T> void expire(T key, long time, TimeUnit timeUnit) {
        redisTemplate.expire(key, time, timeUnit);
    }

    public static <T> long ttl(T key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }

}
